package com.rules.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rules.admin.dao.SysGroupDao;
import com.rules.admin.entity.SysGroup;
import com.rules.admin.entity.SysGroupUserRole;
import com.rules.admin.service.SysGroupService;
import com.rules.admin.service.SysGroupUserRoleService;
import com.rules.admin.vo.RuleUser;
import com.rules.admin.login.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupDao, SysGroup> implements SysGroupService {

   @Autowired
   private SysGroupUserRoleService sysGroupUserRoleService;
   @Autowired
   private UserHolder<RuleUser> userHolder;


   public List<SysGroup> get(long id) {

      List<SysGroupUserRole> sysGroupUserRoles = this.sysGroupUserRoleService.getByUserId(id);
      LambdaQueryWrapper<SysGroup> queryWrapper = new LambdaQueryWrapper<>();
      List<Long> list = new ArrayList();
      if (sysGroupUserRoles.size() != 0) {
         for(int i = 0; i < sysGroupUserRoles.size(); ++i) {
            list.add(sysGroupUserRoles.get(i).getGroupId());
         }
         queryWrapper.in(SysGroup::getId,list);
      }
      return this.list(queryWrapper);
   }

   public List<SysGroup> get(HttpServletRequest request) {
      RuleUser ruleUser = (RuleUser)this.userHolder.getUser();
      List<SysGroupUserRole> sysGroupUserRoles = this.sysGroupUserRoleService.getByUserId(ruleUser.getId());
      List<Long> list = new ArrayList();

      for(int i = 0; i < sysGroupUserRoles.size(); ++i) {
         if (sysGroupUserRoles.get(i).getGroupId() == 6199398653883322368L) {
            return this.list();
         }
         list.add(sysGroupUserRoles.get(i).getGroupId());
      }

      LambdaQueryWrapper<SysGroup> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.in(SysGroup::getId,list);
      return this.list(queryWrapper);

   }

   public void deleteByGroup(SysGroup group) {
      this.sysGroupUserRoleService.deleteByGroupId(group.getId());
      this.removeById(group.getId());
   }

   public Boolean getAdmin() {
      return true;
   }
}
